<template>
  <div style="color: black">
    <el-row type="flex" align="middle" style="margin-bottom: 10px">
      <el-col :span="8" style="display: flex; align-items: center"
        >资料名称：<el-input
          style="flex: 1"
          v-model="name"
          placeholder="请选择资料名称"
        ></el-input
      ></el-col>
    </el-row>
    <el-row type="flex" align="middle" style="margin-bottom: 10px">
      <el-col :span="5">
        <el-button icon="el-icon-plus" type="primary" @click="addHandler"
          >新增</el-button
        >
        <el-button
          icon="el-icon-download"
          type="primary"
          @click="bulkExportHandler"
          >批量导出</el-button
        >
      </el-col>
      <el-col :span="15"></el-col>
      <el-col :span="4" style="text-align: right">
        <el-button type="primary" @click="searchHandler">查询</el-button>
        <el-button plain @click="ResetHandler">重置</el-button>
      </el-col>
    </el-row>
    <el-table
      :data="renderData"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
      :header-cell-style="{ background: '#606266', color: '#fff' }"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column
        prop="projectName"
        label="所属项目"
        align="center"
        width="200"
      />
      <el-table-column prop="name" label="资料名称" align="center" />
      <el-table-column prop="path" label="文档链接" align="center">
        <template slot-scope="scope">
          <span
            v-if="scope.row.path == null"
            style="color: rgb(202, 202, 202); font-size: 0.8rem"
            >暂无文件链接</span
          >
          <div v-else>
            <a
              class="linkp"
              v-for="(item, index) in scope.row.path"
              :key="index"
              style="color: #9ccdff"
              :href="item.filePath"
            >
              {{ item.name }}
            </a>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="100">
        <template slot-scope="scope">
          <el-button type="text" @click="editHandler(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="text"
            style="color: #f56c6c"
            @click="deleteProcessDataApi({ idList: [scope.row.id] })"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
    <!-- 新增/编辑 -->
    <el-dialog
      :title="editTitle"
      :visible.sync="editShow"
      width="30%"
      append-to-body
      :destroy-on-close="false"
      :modal="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="editForm" label-width="80">
        <el-form-item label="所属项目：">
          <el-select
            style="width: calc(100% - 100px)"
            v-model="editForm.projectId"
            placeholder="请选择"
          >
            <el-option
              v-for="item in projectOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="资料名称：">
          <el-input
            style="width: calc(100% - 100px)"
            v-model="editForm.name"
            placeholder="请输入资料名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="相关文件：">
          <el-upload
            style="width: calc(100% - 100px); color: rgb(199, 199, 199)"
            class="upload-demo"
            :action="uploadUrl"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            multiple
            :auto-upload="false"
            :on-change="handleChange"
            :file-list="editForm.docLink"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip" style="margin-left: 20%">
              只能上传doc/pdf文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editShow = false">取 消</el-button>
        <el-button type="primary" @click="saveHandler">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getProcessDataPage,
  saveProcessData,
  updateProcessData,
  deleteProcessData,
  uploadProcessData,
} from "../../../http/inTellingSchedule/processData.js";
import { getProjectList } from "/src/http/inTellingSchedule/userMg.js";
export default {
  data() {
    return {
      currentPage: 1,
      pageSize: 10,
      total: 0,
      isSearch: false,
      editShow: false,
      editTitle: "新增",
      name: "",
      renderData: [],
      // tableData: [
      //   {
      //     id: 1,
      //     projectName: '成都地铁13号线轨道1工区',
      //     name: '成都地铁10、13号线日交班会会议纪要（2023.09.18）',
      //     docLink: null,
      //   },
      //   {
      //     id: 2,
      //     projectName: '成都地铁13号线轨道2工区',
      //     name: '双流地铁10、13号线日交班会会议纪要（2023.09.19）',
      //     docLink: [
      //       {
      //         name: '测试文件.doc',
      //         size: 10240,
      //         type: 'application/msword',
      //         filePath:
      //           'blob:http://localhost:8080/9114e452-fc93-4c39-a0ea-6c28dabc082d',
      //       },
      //     ],
      //   },
      // ],
      //   edit
      editForm: {
        id: null,
        projectId: null,
        name: "",
        docLink: [],
      },
      uploadUrl: "",
      projectOptions: [],
      multipleSelection: [],
    };
  },

  mounted() {
    this.getProcessDataPageApi();
  },

  methods: {
    // 搜索
    searchHandler() {
      this.isSearch = true;
      this.getProcessDataPageApi(1, this.pageSize, this.name);
    },
    // 重置
    ResetHandler() {
      this.isSearch = false;
      this.name = "";
      this.getProcessDataPageApi(1, 10);
    },
    // 新增,
    addHandler() {
      this.editTitle = "新增";
      this.editShow = true;
      this.editForm = {
        id: null,
        projectId: null,
        name: "",
        docLink: [],
      };
      if (this.projectOptions.length == 0) {
        this.getProjectListApi();
      } else {
        return;
      }
    },
    // 编辑
    editHandler(row) {
      this.editTitle = "编辑";
      this.editForm = row;
      this.editShow = true;
      if (this.projectOptions.length == 0) {
        this.getProjectListApi();
      } else {
        return;
      }
    },
    // 文件上传
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    // 预览
    handlePreview(file) {
      console.log(file);
    },
    beforeRemove(file, fileList) {
      console.log(":fileList:: ", fileList);
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleChange(file, fileList) {
      console.log(file, fileList);
      this.editForm.docLink = fileList;
      // 本地服务器路径
      //   console.log(URL.createObjectURL(file.raw))
      // 本地电脑路径
      // console.log(document.getElementsByClassName("el-upload__input")[0].value);
    },
    // save
    saveHandler() {
      if (this.editForm.docLink) {
        this.editForm.docLink.forEach((el) => {
          el.filePath = URL.createObjectURL(el.raw);
        });
      }

      if (this.editTitle === "新增") {
        this.saveProcessDataApi(this.editForm);
      } else {
        this.updateProcessDataApi(this.editForm);
      }
      this.editShow = false;
    },
    // 批量导出
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log("this.multipleSelection::: ", this.multipleSelection);
    },
    bulkExportHandler() {
      this.multipleSelection.forEach((el) => {
        if (el.docLink !== null) {
          el.docLink.forEach((item) => {
            var blob = new Blob([item.filePath], {
              type: "application/octet-stream;chartset=UTF-8",
            });
            var url = window.URL.createObjectURL(blob);
            var a = document.createElement("a");
            a.href = url;
            //文件名
            a.download = item.name;
            a.click();
          });
        }
      });
    },

    // 当前页
    handleCurrentChange(v) {
      this.currentPage = v;
      if (this.isSearch === true) {
        this.getProcessDataPageApi(v, this.pageSize, this.name);
      } else {
        this.getProcessDataPageApi(v, this.pageSize);
      }
    },
    // 当前几条
    handleSizeChange(v) {
      this.pageSize = v;
      if (this.isSearch === true) {
        this.getProcessDataPageApi(1, v, this.name);
      } else {
        this.getProcessDataPageApi(1, v);
      }
    },
    /**
     * 接口
     */
    // 查询项目列表
    getProjectListApi() {
      getProjectList().then((res) => {
        if (res.code == 200) {
          this.projectOptions = res.data;
        }
      });
    },
    // 分页查询项目资料
    getProcessDataPageApi(pageNum = 1, pageSize = 10, name = "") {
      let params = { pageNum, pageSize, name };
      getProcessDataPage(params).then((res) => {
        if (res.code == 200) {
          this.renderData = res.data.records;
          this.total = res.data.total;
        }
      });
    },
    // 保存项目资料
    saveProcessDataApi(params) {
      saveProcessData(params).then((res) => {
        if (res.code == 200) {
          this.$message.success("保存成功");
          this.currentPage = Math.ceil((this.total + 1) / this.pageSize);
          this.getProcessDataPageApi(
            this.currentPage,
            this.pageSize,
            this.name
          );
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 编辑项目资料
    updateProcessDataApi(params) {
      updateProcessData(params).then((res) => {
        if (res.code == 200) {
          this.$message.success("编辑成功");
          this.getProcessDataPageApi(
            this.currentPage,
            this.pageSize,
            this.name
          );
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 删除项目资料
    deleteProcessDataApi(params) {
      this.$confirm("确定要删除该项吗", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消", //相当于 取消按钮
        type: "warning",
      })
        .then(() => {
          deleteProcessData(params).then((res) => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this.currentPage =
                this.total % this.pageSize == 1
                  ? this.currentPage - 1
                  : this.currentPage;
              this.getProcessDataPageApi(
                this.currentPage,
                this.pageSize,
                this.name
              );
            } else {
              this.$message.error(res.message);
            }
          });
        })
        .catch(() => {
          this.$message.info("取消了删除");
        });
    },
    // 上传项目资料
    uploadProcessDataApi(params) {
      uploadProcessData(params).then((res) => {
        if (res.code == 200) {
          this.$message.success("上传成功");
        } else {
          this.$message.error(res.message);
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.linkp {
  cursor: pointer;
}
.linkp:hover {
  color: #409eff;
}
:deep(.el-upload-list) {
  margin-left: 20%;
}
:deep(.el-dialog__header) {
  background-color: rgb(43, 43, 53);
}
:deep(.el-dialog__title) {
  color: #fff;
}
</style>
